import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { routerRedux } from 'dva/router';
import { connect } from 'dva';
import {
  Table,
  Icon,
  Divider,
  Form,
  Select,
  DatePicker,
  Input,
  Card,
  Tag,
  Avatar,
  Checkbox,
  Rate,
  Progress,
  Button,
  Dropdown,
  Row,
  Col,
  Modal,
  Spin,
  message,
  Collapse,
  Upload,
  Radio,
} from 'antd';
import querystring from 'querystring';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import ImageUploader from '../../../components/Falcon/Attachment/ImageUploader';
import ApplyOrderDisplayer from '../../../components/Falcon/ApplyOrderDisplayer';
import DescriptionList from 'components/DescriptionList';
import { solo } from '../../../common/solo';
import styles from './style.less';
import { wrapFileList } from '../../../utils/utils';

const Panel = Collapse.Panel;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const Option = Select.Option;
const { Description } = DescriptionList;

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 18,
  },
};

@connect(({ risk, apply }) => ({
  risk,
  apply,
}))
@Form.create()
export default class HomeVisitDetail extends PureComponent {
  state = {
    projectId: '',
    taskId: '',
    imageMap: {
      familyVisit: [],
    },

    attachmentMap: {
      signVideo: [],
      videoSign: [],
    },

    homeVisitLoading: false,
  };

  signVideoData = {
    projectId: this.state.projectId, //业务ID
    customerId: '', //客户ID
    attachType: '1', //0：图片；1：视频
    attachKind: '9390', //附件种类
    type: '家访视频', //图片类型
  };

  videoSignData = {
    projectId: this.state.projectId, //业务ID
    customerId: '', //客户ID
    attachType: '1', //0：图片；1：视频
    attachKind: '9490', //附件种类
    type: '面签视频', //图片类型
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    const params = querystring.parse(location.search.slice(1));
    this.setState({
      projectId: params.id,
      taskId: params.taskId,
    });
    (this.signVideoData.projectId = params.id),
      (this.videoSignData.projectId = params.id),
      dispatch({
        type: 'risk/showHomeVisit',
        payload: {
          projectId: params.id,
        },
        callback: () => {
          const { risk: { riskHomeVisitDetails } } = this.props;
          // console.log("riskHomeVisitDetails", riskHomeVisitDetails)
          let HomeVisitImg = this.state.imageMap;
          if (riskHomeVisitDetails.picAttach.length > 0) {
            for (let i = 0; i < riskHomeVisitDetails.picAttach.length; i++) {
              HomeVisitImg.familyVisit.push({
                uid: riskHomeVisitDetails.picAttach[i],
                key: riskHomeVisitDetails.picAttach[i],
                name: riskHomeVisitDetails.picAttach[i],
                status: 'done',
                url: solo.imgShow + riskHomeVisitDetails.picAttach[i],
              });
            }
          }
          let attachmentMap = this.state.attachmentMap; //上传的视频
          if (riskHomeVisitDetails.videoAttach.length > 0) {
            for (let i = 0; i < riskHomeVisitDetails.videoAttach.length; i++) {
              attachmentMap.signVideo.push({
                uid: riskHomeVisitDetails.videoAttach[i],
                key: riskHomeVisitDetails.videoAttach[i],
                name: riskHomeVisitDetails.videoAttach[i],
                status: 'done',
                url: solo.fileDownload + riskHomeVisitDetails.videoAttach[i],
              });
            }
          }
          if (riskHomeVisitDetails.videoSignAttach.length > 0) {
            //视频面签
            for (let i = 0; i < riskHomeVisitDetails.videoSignAttach.length; i++) {
              attachmentMap.videoSign.push({
                uid: riskHomeVisitDetails.videoSignAttach[i],
                key: riskHomeVisitDetails.videoSignAttach[i],
                name: riskHomeVisitDetails.videoSignAttach[i],
                status: 'done',
                url: solo.fileDownload + riskHomeVisitDetails.videoSignAttach[i],
              });
            }
          }
          this.setState({
            imageMap: HomeVisitImg,
            attachmentMap,
            homeVisitLoading: true,
          });
        },
      });

    window.addEventListener('resize', this.resizeFooterToolbar);
  }
  componentWillUnmount() {
    window.removeEventListener('resize', this.resizeFooterToolbar);
  }

  handleHomeVisitDetailSubmit = () => {
    const { dispatch } = this.props;
    const { validateFieldsAndScroll } = this.props.form;
    validateFieldsAndScroll((error, values) => {
      if (!error) {
        dispatch({
          type: 'risk/commitHomeVisit',
          payload: {
            id: this.state.projectId,
            taskId: this.state.taskId,
            ...values,
          },
          callback: () => {
            const { risk: { riskResult } } = this.props;
            if (riskResult.code == '200') {
              message.success('提交成功');
              dispatch(routerRedux.push(`/risk/homeVisitList`));
            } else {
              message.error(riskResult.message);
            }
          },
        });
      }
    });
  };

  handleImageUploaded = (fieldName, fileList) => {
    switch (fieldName) {
      case '家访照片':
        this.setState({
          imageMap: { ...this.state.imageMap, familyVisit: fileList },
        });
        break;
    }
  };

  handleRemoveFile = file => {
    const { dispatch } = this.props;
    let key = null;
    if (file.response) {
      key = file.response.body.key;
    } else {
      key = file.key;
    }
    dispatch({
      type: 'apply/deleteFile',
      payload: {
        fileId: key,
      },
      callback: () => {
        const { apply: { applyResult } } = this.props;
        if (applyResult.code == 200) {
          message.success('删除成功');
          dispatch({
            type: 'risk/showHomeVisit',
            payload: {
              projectId: this.state.projectId,
            },
          });
        } else {
          message.error(applyResult.message);
        }
      },
    });
  };

  handleAttachmentUploadChange = (info, fieldName) => {
    const fileList = wrapFileList(info);
    // console.log("handleAttachmentUploadChange",fileList )
    const attachmentMap = { ...this.state.attachmentMap };
    attachmentMap[fieldName] = fileList;
    this.setState({
      attachmentMap,
    });
  };

  handleRemoveImage = (fieldName, fileInfo) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'apply/deleteFile',
      payload: {
        fileId: fileInfo.key,
      },
    });
  };

  render() {
    const { risk: { riskHomeVisitDetails, riskLoading, riskHomeVisitLoading } } = this.props;
    const { getFieldDecorator } = this.props.form;

    const defaultAttachmentUploadProps = {
      name: 'file',
      action: solo.uploadImg,
      multiple: true,
      headers: {
        authorization: 'authorization-text',
      },
    };

    const videoFileUploadProps = {
      ...defaultAttachmentUploadProps,
      defaultFileList: this.state.attachmentMap.signVideo,
      onChange: info => {
        this.handleAttachmentUploadChange(info, 'signVideo');
      },
      onRemove: file => {
        this.handleRemoveFile(file);
      },
    };

    const videoFaceFileUploadProps = {
      ...defaultAttachmentUploadProps,
      defaultFileList: this.state.attachmentMap.videoSign,
      onChange: info => {
        this.handleAttachmentUploadChange(info, 'videoSign');
      },
      onRemove: file => {
        this.handleRemoveFile(file);
      },
    };

    return (
      <PageHeaderLayout title="家访调查" content="请到客户家庭现场调查，并填写此表单">
        {/* {JSON.stringify(riskHomeVisitDetails)} */}
        {riskLoading ? (
          <div className={styles.spinContainer}>
            <Spin size="large" />
          </div>
        ) : (
          riskHomeVisitDetails && (
            <div>
              <Card title="业务信息" className={styles.preCheckFormCard}>
                {/* <ApplyOrderDisplayer /> */}
                <DescriptionList style={{ marginBottom: 32 }} col="3">
                  <Description term="客户名称">{riskHomeVisitDetails.custName}</Description>
                  <Description term="证件号">{riskHomeVisitDetails.idcard}</Description>
                  <Description term="家庭住址">{riskHomeVisitDetails.residDetail}</Description>
                  <Description term="经销商">{riskHomeVisitDetails.dealerName}</Description>
                  <Description term="工作地址">{riskHomeVisitDetails.corpDetail}</Description>
                  <Description term="资产种类">
                    {riskHomeVisitDetails.assetType == 1 ? '新车' : '二手车'}
                  </Description>
                  <Description term="所购车型">{riskHomeVisitDetails.carType}</Description>
                  <Description term="车价">{riskHomeVisitDetails.dealerPrice}</Description>
                  <Description term="分期数">
                    {riskHomeVisitDetails.loanDuration == null
                      ? 0
                      : riskHomeVisitDetails.loanDuration}
                  </Description>
                  <Description term="贷款金额">{riskHomeVisitDetails.loanAmt}</Description>
                </DescriptionList>
              </Card>
              {this.state.homeVisitLoading && (
                <Card title="家访信息" className={styles.preCheckFormCard}>
                  <Form className={styles.preCheckForm}>
                    <FormItem label="家访地址" {...formItemLayout}>
                      {getFieldDecorator('homeAddress', {
                        initialValue: riskHomeVisitDetails.homeAddress,
                      })(
                        <Select>
                          <Option value="1">工作地址</Option>
                          <Option value="2">家庭住址</Option>
                        </Select>
                      )}
                    </FormItem>
                    <FormItem label="上传照片" {...formItemLayout}>
                      <ImageUploader
                        maxCount={10} //fieldName="家访照片"
                        key={1}
                        size="large"
                        showRemoveIconType={true}
                        onRemoveImage={this.handleRemoveImage}
                        attachmentData={{
                          projectId: this.state.projectId, //业务ID
                          customerId: '', //客户ID
                          attachType: '0', //0：图片；1：视频
                          attachKind: '1310', //附件种类
                          type: '家访照片', //图片类型
                        }}
                        fileList={this.state.imageMap.familyVisit}
                        onImageUploaded={this.handleImageUploaded}
                      />
                    </FormItem>

                    <FormItem label="上传视频" {...formItemLayout}>
                      <Upload {...videoFileUploadProps} data={this.signVideoData}>
                        <Button icon="upload">上传文件</Button>
                        <div style={{ lineHeight: '40px', color: '#999999' }} />
                      </Upload>
                    </FormItem>

                    <FormItem label="视频面签" {...formItemLayout}>
                      {/* <ImageUploader /> */}
                      <Upload {...videoFaceFileUploadProps} data={this.videoSignData}>
                        <Button icon="upload">上传文件</Button>
                        <div style={{ lineHeight: '40px', color: '#999999' }} />
                      </Upload>
                    </FormItem>

                    {/* <FormItem label="人脸识别" {...formItemLayout}>
                    {getFieldDecorator('faceRecognitionState', {
                      initialValue: riskHomeVisitDetails.faceRecognitionState,
                    })(
                      <RadioGroup>
                        <Radio value={1}>通过</Radio>
                        <Radio value={0}>不通过</Radio>
                      </RadioGroup>
                    )}
                  </FormItem> */}
                  </Form>
                </Card>
              )}

              <Card title="家访结论" className={styles.preCheckFormCard}>
                <Form className={styles.preCheckForm}>
                  <FormItem label="家访意见" {...formItemLayout}>
                    {getFieldDecorator('homeVisitNote', {
                      initialValue: riskHomeVisitDetails.homeVisitNote,
                    })(<TextArea rows={4} placeholder="请输入意见说明" />)}
                  </FormItem>
                  <FormItem
                    wrapperCol={{
                      xs: { span: 24, offset: 0 },
                      sm: {
                        span: formItemLayout.wrapperCol.span,
                        offset: formItemLayout.labelCol.span,
                      },
                    }}
                    label=""
                  >
                    <Button
                      type="primary"
                      onClick={this.handleHomeVisitDetailSubmit}
                      loading={riskHomeVisitLoading}
                    >
                      提交
                    </Button>
                  </FormItem>
                </Form>
              </Card>
            </div>
          )
        )}
      </PageHeaderLayout>
    );
  }
}
